package com.run.serial;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.File;
import java.util.logging.Logger;
//import android.hardware.SerialManager;
//import android.hardware.SerialPort;

public class SerialUtils {
    private static final String TAG = "SerialUtils";
    private static SerialUtils serialUtils = null;

    private SerialPort serialPort = null;

    private boolean openSuccess = false;

    static boolean isSendData = false;
    static boolean isReadData = false;

    private SerialUtils() {
    }

    public static SerialUtils getInstance() {
        if (serialUtils == null) {
            synchronized (SerialUtils.class) {
                if (serialUtils == null) {
                    serialUtils = new SerialUtils();
                }
            }
        }
        return serialUtils;
    }

    /**
     * 该方法建议值Application执行
     *
     //* @param context 上下文
     * @param baud    设置波特率,9600的倍数,例如:38400
     * @param strPort 设置串口路径,例如:/dev/ttSy5
     * @return 是否正确打开串口
     */
    public synchronized boolean init(int baud, String strPort) {//@NonNull Context context,
        if (openSuccess) {
            throw new RuntimeException("serial is open succeed");
        }
        int baudRate;
        if (baud <= 0) {
            throw new IllegalArgumentException("the baud is wrongful,baud must be baud > 0");
        }
        if ((baud % 50) != 0) {
//            throw new IllegalArgumentException("the baud is wrongful,baud must be baud % 9600 == 0");
        }
        baudRate = baud;

        String port;
        if (strPort.equals("")) {
            throw new IllegalArgumentException("the strPort is wrongful,strPort not around \"\"");
        }
        port = strPort;

        try {
            String SERVER_STRING = "serial";
//            @SuppressLint("WrongConstant")
//			SerialManager serialManager = (SerialManager) context.getSystemService(SERVER_STRING);
            //打开串口通信
            openSuccess = false;
//			serialPort = serialManager.openSerialPort(port, baudRate);
            serialPort = new SerialPort(new File(port), baudRate, 0);
            SerialTxData.getInstance().setSerialPort(serialPort);
            openSuccess = true;
            Log.d(getClass().getSimpleName(), "===========openSuccess====================");
        } catch (Exception e) {
            e.printStackTrace();
            openSuccess = false;
        }
        return openSuccess;
    }

    public synchronized void regRxDataCallBack(@NonNull RxDataCallBack callBack) {
        SerialTxData.getInstance().setRxDataCallBack(callBack);
        SerialRxData.getInstance().setRxDataCallBack(callBack);
    }

    public synchronized void unRegRxDataCallBack() {
        SerialRxData.getInstance().setRxDataCallBack(null);
    }

    /**
     * <br>开启串口读写线程前必须先调用init(Context context)</br>
     * <br>最好在Application中执行</br>
     */
    public synchronized void startTask() {
        if (!openSuccess) {
            throw new RuntimeException("please call method init(@NonNull Context context, int baud, String strPort)");
        }
        ThreadPoolManager.getInstance().createThreadPool();

        isReadData = true;
        ThreadPoolManager.getInstance().addTask(new SerialRxDataTask(serialPort));

        isSendData = true;
        ThreadPoolManager.getInstance().addTask(new SerialTxDataTask(SerialTxData.getInstance(), serialPort));
    }

    public synchronized void sendPackage(byte[] data) {
        if (openSuccess) {
            SerialTxData.getInstance().sendPackageEnQueue(data);
        }
    }

    public boolean stopSerial() {
        unRegRxDataCallBack();
        isReadData = false;
        isSendData = false;
        openSuccess = false;
        try {
            if (serialPort != null) {
                serialPort.close();
            }
        } catch (Exception ignore) {
            return false;
        }
        return true;
    }

    public boolean isOpenSuccess() {
        return openSuccess;
    }
}